package com.rentong.wx.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.rentong.basic.BusinessException;
import net.sf.json.JSONObject;

import java.util.Map;

public class SendSMS {

    private static int code() {
        int intFlag = (int) (Math.random() * 1000000);

        String flag = String.valueOf(intFlag);
        if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
            return intFlag;
        } else {
            intFlag = intFlag + 100000;
            return intFlag;
        }
    }


    public static String sendSMS(String phone) {
        String code = code() + "";
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tJqW1XXCpRSKGXtg6pz", "f8D3qXYD9WM0vfhBjCvxGvxUOqgjTJ");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "湖州宏浩餐饮管理");
        request.putQueryParameter("TemplateCode", "SMS_314695674");
//        request.putQueryParameter("TemplateParam", JSON.toJSONString(message));
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());

            JSONObject jsonObject = JSONObject.fromObject(response.getData());

            Map<String, Object> map = (Map<String, Object>) jsonObject;

            if ("OK".equals(map.get("Message").toString())) {
                return code;
            } else {
                throw new BusinessException("验证码发送失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new BusinessException("验证码发送失败！");
    }




}
